<?php

namespace app\api\controller;

use think\Controller;
use think\Db;
use app\common\model\WxUser as WxUserModel;
use app\common\model\Users as UsersModel;
use app\common\model\Csuser as CsuserModel;
use app\common\util\WechatThirdUtil;
use think\Request;

class User extends Controller
{
    protected $config;
    protected $wx_user;
    protected $users_model;
    protected $csuser_model;
    private $request_uri;
    private $request_uri3;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->csuser_model = new CsuserModel();
        $this->users_model = new UsersModel();
        $this->config = $this->wx_user->find();
        $this->request_uri = NODE_URL.'/receiveMsg';
        $this->request_uri3 = NEW_NODE_URL.'/receiveMsg';
    }
    /*
     * 用 client : news
     * */
    public function sengMsgForUser(){
        // 發送消息給用戶
        if(Request::instance()->isPost()) {
            $data = Request::instance()->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = isset($data['customerService']) ? $data['customerService'] : '';
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            if (!empty($customerService)) {
                $result = $wechatObj->appointSendMsgToOne($openid, $content, $customerService);
            } else {
                $result = $wechatObj->sendMsgToOne($openid, $content);
            }
            if ($result) {
                $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                $post_arr = [
                    'type' => $data['type'],
                    'content' => $content, //消息文本
                    'openid' => $openid, //用户openid
                    'appid' => $appid, //对应公众号appid
                    'cs_id' => $data['cs_id'], //客服id
                    'send_time' => $data['send_time'], //发送时间
                    'send_type' => '1002',
                    'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                    'fromname' => $pid == 0 ? $pid : $data['cs_id'] ,  // 消息来自于组长
                ];
                // 判断消息的发送人  组长还是组员

                //测试储存链接的外部数据库
                //获取储存对应数据库名
                $sqlname = 'chatlog' . $data['cs_id'] % 10;
                $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                if ($ret) {// 判断get里面有没有 client : news
//                      $get_data = Request::instance()->get();
//                      $isnew = isset($get_data['client']) ? $get_data['client'] : 0;
//                      $infomation = '';
//                      if($isnew){
//                          // 消息来自新客户端,需要转发给老客户端
// //                         $infomation = '消息来自新客户端,需要转发给老客户端';
// //                         file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
//                          $send_result = $this->send($this->request_uri,$post_arr);
// //                         file_put_contents('./requestMsg.log','轉發結果:'.$send_result."\n",FILE_APPEND);
//                      }else{
//                          // 消息来自老客户端,需要转发给新客户端
// //                         $infomation = '消息来自老客户端,需要转发给新客户端';
// //                         file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
//                          $send_result = $this->send($this->request_uri3,$post_arr);
//                      }
                    return json_encode(['status' => 1, 'msg' => '发送成功', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode(['status' => -1, 'error' => '发送失败'], JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status' => -1, 'error' => '非法請求'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 向用户发送文本信息.V 1.0
     */
    public function sengMsgForUser_bk()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];

            $customerService = isset($data['customerService']) ? $data['customerService'] : '';
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            if (!empty($customerService)) {
                $result = $wechatObj->appointSendMsgToOne($openid, $content, $customerService);
            } else {
                $result = $wechatObj->sendMsgToOne($openid, $content);
            }

            if ($result) {
                $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');

                $post_arr = [
                    'type' => $data['type'],
                    'content' => $content, //消息文本
                    'openid' => $openid, //用户openid
                    'appid' => $appid, //对应公众号appid
                    'cs_id' => $data['cs_id'], //客服id
                    'send_time' => $data['send_time'], //发送时间
                    'send_type' => '1002',
                    'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                ];
                //测试储存链接的外部数据库
                //获取储存对应数据库名
                $sqlname = 'chatlog'.$data['cs_id'] % 10;

                $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                // $ret = Db::name('chatlog')->insert($post_arr);
                if ($ret) {

                    return json_encode(['status' => 1, 'msg' => '发送成功', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }
            } else {
                return json_encode(['status' => -1, 'error' => '发送失败'], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => '煞笔，哈哈'], JSON_UNESCAPED_UNICODE);
        }
    }

    /*
     * 向用戶發送文本消息 V 1.1
     * 新版判斷是否是新客戶端 访问速度慢,抛弃
     * */
    public function sengMsgForUser_haad(){
        // 获取head里面的 version
        $head_data = Request::instance()->header();
        // 發送消息給用戶
        if(Request::instance()->isPost()){
            $data = Request::instance()->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $content = $data['content'];
            $customerService = isset($data['customerService']) ? $data['customerService'] : '';
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            if (!empty($customerService)) {
                $result = $wechatObj->appointSendMsgToOne($openid, $content, $customerService);
            } else {
                $result = $wechatObj->sendMsgToOne($openid, $content);
            }

            if ($result) {
                $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                $post_arr = [
                    'type' => $data['type'],
                    'content' => $content, //消息文本
                    'openid' => $openid, //用户openid
                    'appid' => $appid, //对应公众号appid
                    'cs_id' => $data['cs_id'], //客服id
                    'send_time' => $data['send_time'], //发送时间
                    'send_type' => '1002',
                    'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                ];
                //测试储存链接的外部数据库
                //获取储存对应数据库名
                $sqlname = 'chatlog'.$data['cs_id'] % 10;

                $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
                $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                // $ret = Db::name('chatlog')->insert($post_arr);
                if ($ret) {
                    // 判斷發送的客戶端,轉發給另外一端
                    $isnew = isset($head_data['version']) ? $head_data['version'] : 0;
                    $infomation = '';
                    if($isnew){
                        // 消息来自新客户端,需要转发给老客户端
                        $infomation = '消息来自新客户端,需要转发给老客户端';
                        file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                        $send_result = $this->send($this->request_uri,$post_arr);
                        file_put_contents('./requestMsg.log','轉發結果:'.$send_result."\n",FILE_APPEND);
                    }else{
                        // 消息来自老客户端,需要转发给新客户端
                        $infomation = '消息来自老客户端,需要转发给新客户端';
                        file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                        $send_result = $this->send($this->request_uri3,$post_arr);
                        file_put_contents('./requestMsg.log','轉發結果:'.$send_result."\n",FILE_APPEND);
                    }
                    return json_encode(['status' => 1, 'msg' => '发送成功', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }
            } else {
                return json_encode(['status' => -1, 'error' => '发送失败'], JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status' => -1, 'error' => '非法請求'], JSON_UNESCAPED_UNICODE);
        }
    }



    /*
     * 普通向用户发送图片消息
     * 加上可以群发图片消息 V 1.0
     * */
    public function sengImgForUser()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 判断media_id 是否为空,如果不存在就上传图片,存在就直接发送
            if(empty($data['media_id'])){
                $file = $this->request->file('image');
                $result = $this->resource($data, $file, 'image');
                if ($result) {
                    return $result;
                } else {
                    return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
                }
            }else{
                $result = null;
                $appid = $data['appid'];
                $openid = $data['openid'];

                $customerService = isset($data['customerService']) ? $data['customerService'] : '';
                $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
                $wechatObj = new WechatThirdUtil($this->config, $author_wx);


                if (!empty($customerService)) {
                    $result = $wechatObj->appointSendMediaToOne($data['openid'], $data['media_id'], 'image', $customerService);
                }else{
                    $result = $wechatObj->sendMediaToOne($data['openid'], $data['media_id'], 'image');
                }

                if ($result) {
                    $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                    $post_arr = [
                        'type' => $data['type'],
                        'content' =>$data['content'], //图片路径
                        'openid' => $data['openid'], //用户openid
                        'appid' => $data['appid'], //对应公众号appid
                        'cs_id' => $data['cs_id'], //客服id
                        'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                        'send_type' => '1002',
                        'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                    ];

                    //获取储存对应数据库名
                    $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
                    $sqlname = 'chatlog'.$data['cs_id'] % 10;
                    $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                    $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                    // $ret = Db::name('chatlog')->insert($post_arr);
                    if ($ret) {
                        // $get_data = Request::instance()->get();
                        // $isnew = isset($get_data['client']) ? $get_data['client'] : 0;
                        // // $infomation = '';
                        // if($isnew){
                        //     // 消息来自新客户端,需要转发给老客户端
                        //  // $infomation = '消息来自新客户端,需要转发给老客户端';
                        //  // file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                        //     $send_result = $this->send($this->request_uri,$post_arr);
                        //  // file_put_contents('./requestMsg.log','新客户端轉發結果:'.$send_result."\n",FILE_APPEND);
                        // }else{
                        //     // 消息来自老客户端,需要转发给新客户端
                        //  // $infomation = '消息来自老客户端,需要转发给新客户端';
                        //  // file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                        //     $send_result = $this->send($this->request_uri3,$post_arr);
                        //     // file_put_contents('./requestMsg.log','老客户端轉發結果:'.$send_result."\n",FILE_APPEND);
                        // }
                        return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $data['content'], 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                    }else{
                        return json_encode(['status' => 303, 'error' => '写入数据库失败'], JSON_UNESCAPED_UNICODE);
                    }
                } else {
                    return json_encode(['status' => 301, 'error' => '发送图片失败'], JSON_UNESCAPED_UNICODE);
                }
            }
        } else {
            return json_encode(['status' => 404, 'error' => '非法请求'], JSON_UNESCAPED_UNICODE);
        }
    }

    /*普通向用户发送图片消息
     * 加上可以群发图片消息
     * 加上新老客户端互转 V 1.1
     * */
    public function sengImgForUser_new()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 判断media_id 是否为空,如果不存在就上传图片,存在就直接发送
            if(empty($data['media_id'])){
                $file = $this->request->file('image');
                $result = $this->resource($data, $file, 'image');
                if ($result) {
                    return $result;
                } else {
                    return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
                }
            }else{
                $result = null;
                $appid = $data['appid'];
                $openid = $data['openid'];

                $customerService = isset($data['customerService']) ? $data['customerService'] : '';
                $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
                $wechatObj = new WechatThirdUtil($this->config, $author_wx);

                if (!empty($customerService)) {
                    $result = $wechatObj->appointSendMediaToOne($data['openid'], $data['media_id'], 'image', $customerService);
                }else{
                    $result = $wechatObj->sendMediaToOne($data['openid'], $data['media_id'], 'image');
                }

                if ($result) {
                    $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
                    $post_arr = [
                        'type' => $data['type'],
                        'content' =>$data['content'], //图片路径
                        'openid' => $data['openid'], //用户openid
                        'appid' => $data['appid'], //对应公众号appid
                        'cs_id' => $data['cs_id'], //客服id
                        'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                        'send_type' => '1002',
                        'pid' => $pid == 0 ? $data['cs_id'] : $pid,
                    ];

                    //获取储存对应数据库名
                    $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
                    $sqlname = 'chatlog'.$data['cs_id'] % 10;
                    $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
                    $this->mo_send_type($author_wx['id'], $author_wx['uid']);
                    // $ret = Db::name('chatlog')->insert($post_arr);
                    if ($ret) {
                        // 判断是否带有新版标识符
                        $get_data = Request::instance()->get();
                        $isnew = isset($get_data['client']) ? $get_data['client'] : 0;
                        $infomation = '';
                        if($isnew){
                            // 消息来自新客户端,需要转发给老客户端
                            $infomation = '图片消息来自新客户端,需要转发给老客户端';
                            file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                            $send_result = $this->send($this->request_uri,$post_arr);
                            file_put_contents('./requestMsg.log','轉發結果:'.$send_result."\n",FILE_APPEND);
                        }else{
                            // 消息来自老客户端,需要转发给新客户端
                            $infomation = '图片消息来自老客户端,需要转发给新客户端';
                            file_put_contents('./requestMsg.log','轉發消息==:'.$infomation."\n",FILE_APPEND);
                            $send_result = $this->send($this->request_uri3,$post_arr);
                            file_put_contents('./requestMsg.log','轉發結果:'.$send_result."\n",FILE_APPEND);
                        }
                        return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $data['content'], 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                    }else{
                        return json_encode(['status' => 303, 'error' => '写入数据库失败'], JSON_UNESCAPED_UNICODE);
                    }
                } else {
                    return json_encode(['status' => 301, 'error' => '发送图片失败'], JSON_UNESCAPED_UNICODE);
                }
            }
        } else {
            return json_encode(['status' => 404, 'error' => '非法请求'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 向用户发送图片信息.
     */
    public function sengImgForUser_old()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file = $this->request->file('image');
            $result = $this->resource($data, $file, 'image');
            if ($result) {
                return $result;
            } else {
                return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => '煞笔，哈哈'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 向用户发送语音信息.
     */
    public function sendVoiceForUser()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file = $this->request->file('voice');
            // dump($file);exit();
            $result = $this->resource($data, $file, 'voice');
            if ($result) {
                return $result;
            } else {
                return json_encode(['status' => -1, 'error' => 'resource upload error'], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => '煞笔，哈哈'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 从微信api获取用户信息.
     *
     * @param appid 公众号appid
     * @param openid 用户openid
     */
    public function getUserInfo($appid, $openid)
    {
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $result = $wechatObj->getFanInfo($openid);
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 从数据库获取用户信息.
     *
     * @param openid 用户id
     */
    public function getSqlUserInfo_bk($openid)
    {
        $result = $this->users_model->alias('u')->where('openid', $openid)->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')->find();
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /*
     * 从数据库获取用户信息.
     * 附带最后一条聊天记录
     * */
    public function getSqlUserInfo($openid)
    {
        // 返回用户信息的同时返回备注信息 users_added
        $result = $this->users_model->alias('u')->where('openid', $openid)->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')->find();
        $last_msg = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $openid)->order('id desc')->limit(1)->select();
        if ($result) {
            return json_encode(['status' => 1, 'result' => $result , 'last_msg' => $last_msg], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 获取聊天记录，包括需要推送的消息.
     *
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function getChatLogAll()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (M('csuser')->where('id', $data['cs_id'])->value('pid') == 0) {
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where('pid', $data['cs_id'])->where('openid', $data['openid'])->order('id desc')->select();
            } else {
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where('cs_id', $data['cs_id'])->where('openid', $data['openid'])->order('id desc')->select();
            }
            if ($result) {
                return json_encode(['status' => 1, 'chatlog' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error']);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }

    /**
     * 获取聊天记录，包括需要推送的消息.
     * ==> 临时改成获取全部聊天记录
     * @param openid 用户openid
     * @param cs_id 客服id
     * @param offset 偏移量
     * @param log_id 聊天记录id
     * @param count 数量
     */
  
    public function getChatLog()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $cs_id = $data['cs_id'];
            $openid = $data['openid'];
            $last_time = isset($data['last_time']) ? $data['last_time'] : '';
            $offset = isset($data['offset']) ? ($data['offset'] < 10 ? $data['offset'] : 10) : 0;
            $count = isset($data['count']) ? ($data['count'] < 10 ? $data['count'] : 10) : 10;
            if (M('csuser')->where('id', $data['cs_id'])->value('pid') == 0) {
                $where = [
                    'pid' => ['eq', $cs_id],
                    'openid' => ['eq', $openid],
                ];
            } else {
                $where = [
                    'cs_id' => ['eq', $cs_id],
                    'openid' => ['eq', $openid],
                ];
            }

            if ($offset != 0) {
                $count = $offset - $count;
            }
            if(empty($last_time)){
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
            }else{
                $where['send_time'] = ['lt', $last_time];
                $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->limit($offset, $count)->order('id desc')->select();
            }

            if ($result) {
                return json_encode(['status' => 1, 'chatlog' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error', 'chatlog' => '']);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'error']);
        }
    }


    /**
     * 获取需要推送的聊天消息.
     *
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function getPushMsg()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq', $data['cs_id']],
                'needsend' => ['eq', 1],
            ];
            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->order('id desc')->select();
            //获取完聊天记录后把状态改回0
            if ($result) {
                Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);

                return json_encode(['status' => 1, 'pushmsg' => $result]);
            } else {
                return json_encode(['status' => -1, 'error' => 'error']);
            }
        }
    }

    /**
     * 已读推送消息，取消推送状态提醒.
     *
     * @param openid 用户openid
     * @param cs_id 客服id
     */
    public function clearPushMsg()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $where = [
                'cs_id' => ['eq', $data['cs_id']],
                'openid' => ['eq', $data['openid']],
                'needsend' => ['eq', 1],
            ];

            $result = Db::connect('db_config_chatlog')->name('chatlog')->where($where)->update(['needsend' => 0]);
            if ($result) {
                return json_encode(['status' => 1, 'msg' => '状态已清除']);
            } else {
                return json_encode(['status' => -1, 'error' => '状态清除失败']);
            }
        }
    }

    /**
     * 给用户打标签.
     *
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function setUserTags()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $appid = $data['appid'];
            // $openid_list[] = $data['openid'];
            $openid = $data['openid'];
            $tagid = $data['tagid'];
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            $result = $wechatObj->batchUsersTag([$openid], $tagid);
            if ($result) {
                $tagid_list = $this->users_model->where('openid', $openid)->value('tagid_list');
                $tagid_list_arr = unserialize($tagid_list);
                $tagid_list_arr[] = $tagid;
                $tagid_list_arr = array_unique($tagid_list_arr);
                // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
                $res = M('users')->where('openid', $openid)->update(['tagid_list' => serialize($tagid_list_arr)]);
                if (!$res) {
                    return json(['status' => -1, 'error' => 'Update user taglist error']);
                } else {
                    return json(['status' => 1, 'msg' => 'ok', 'tagid_list' => $tagid_list_arr]);
                }
            } else {
                return json(['status' => -1, 'msg' => 'Save tag to WeChat failure']);
            }
        } else {
            return json(['status' => -1, 'error' => 'method error']);
        }
    }

    /**
     * 给用户删除标签.
     *
     * @param type appid
     * @param type tagid
     * @param type openid
     */
    public function delUserTags()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $appid = $data['appid'];
            $openid = $data['openid'];
            $tagid = $data['tagid'];
            $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
            $wechatObj = new WechatThirdUtil($this->config, $author_wx);
            $result = $wechatObj->batchCancelUsersTag([$openid], $tagid);
            if ($result) {
                $tagid_list = $this->users_model->where('openid', $openid)->value('tagid_list');
                $tagid_list_arr = unserialize($tagid_list);
                $filp_tagid_list_arr = array_flip($tagid_list_arr); //调换键值
                if (array_key_exists($tagid, $filp_tagid_list_arr)) {
                    unset($filp_tagid_list_arr[$tagid]);
                    $tagid_list_arr = array_flip($filp_tagid_list_arr);
                    $res = M('users')->where('openid', $openid)->update(['tagid_list' => serialize($tagid_list_arr)]);
                    // $res = M('users')->where('openid','IN',implode(',',$openid_list))->update(['tagid_list'=>serialize($tagid_list_arr)]);
                    if ($res) {
                        return json(['status' => 1, 'msg' => 'ok', 'tagid_list' => $tagid_list_arr]);
                    } else {
                        echo M('users')->getLastSql();

                        return json(['status' => -1, 'error' => 'Update user taglist error']);
                    }
                }
            } else {
                return json(['status' => -1, 'msg' => 'Save tag to WeChat failure']);
            }
        } else {
            return json(['status' => -1, 'error' => 'method error']);
        }
    }

    /*
     * 自动获取用户粉丝信息
     * */
    public function getData(){

    }


    /**
     * 自动推送前15个用户信息.
     *
     * @param type cs_id
     */
    public function autoPushMsg($cs_id)
    {
        if (M('csuser')->where('id', $cs_id)->value('pid') == 0) {
            $map = [
                'pid' => ['eq', $cs_id],
            ];
        } else {
            $map = [
                'cs_id' => ['eq', $cs_id],
            ];
        }

        $where = [
            'butt_id' => ['eq', $cs_id],
            'subscribe' => ['eq', 1],
        ];

        //获取聊天时间最晚的
        $openids = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('openid')->order('send_time desc')->limit(50)->column('openid');
        if ($openids != true) {
            return json(['status' => -1, 'error' => 'openids is empty']);
        }
        $result = $this->users_model->field('user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age')->alias('u')->whereIn('openid', $openids)->where('subscribe', 1)
                    ->union("SELECT user_id,sex,openid,headimgurl,nickname,wechat_num,name,phone,age FROM think_users as s LEFT JOIN think_users_added as d ON s.user_id = d.uid WHERE butt_id = {$cs_id} AND subscribe = 1 LIMIT 50")
                    ->join('think_users_added a', 'u.user_id = a.uid', 'LEFT')
                    ->select();

        //获取最晚关注的
        // $result = $this->users_model->alias('u')->where($where)
        //             ->join('think_users_added a','u.user_id = a.uid','LEFT')
        //             ->order('subscribe_time desc')->limit(15)->select();
        if ($result) {
            foreach ($result as $v) {
                $chatlog = Db::connect('db_config_chatlog')->name('chatlog')->where('openid', $v['openid'])->order('send_time DESC')->limit(10)->select();
                $v['chatlog'] = array_reverse($chatlog);
            }

            return json(['status' => 1, 'msg' => 'ok', 'result' => $result]);
        } else {
            return json(['status' => -1, 'error' => 'maybe query error,please check']);
        }
    }

    /**
     * 上传素材资源，返回资源本地路径.
     *
     * @param type image[图片] audio[音频]
     */
    protected function resource($data, $file, $type)
    {
        // file_put_contents('./requestMsgError.log','['.date("Y-m-d H:i:s").'] appid:'.$data['appid']."\n",FILE_APPEND);
        $appid = $data['appid'];
        $openid = $data['openid'];
        $chat_upload = new Chatupload();
        if ($type == 'image') {
            $keyword_arr = $chat_upload->upload($file);
            // $keyword_arr = $file;
        } elseif ($type == 'voice') {
            $keyword_arr = $chat_upload->voiceUpload($file);
        }

        if ($keyword_arr['error'] == 0) {
            $keyword = $keyword_arr['url'];
        } else {
            return false;
        }

        $customerService = isset($data['customerService']) ? $data['customerService'] : '';
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        $chat_resource = null;
        // 判断是否是客户端
        if (!empty($customerService)) {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->appointSendMediaToOne($openid, $chat_resource['media_id'], $type, $customerService);
        } else {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->sendMediaToOne($openid, $chat_resource['media_id'], $type);
        }

        if ($result) {
            $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
            $post_arr = [
                'type' => $data['type'],
                'content' => $keyword, //图片路径
                'openid' => $data['openid'], //用户openid
                'appid' => $data['appid'], //对应公众号appid
                'cs_id' => $data['cs_id'], //客服id
                'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                'send_type' => '1002',
                'pid' => $pid == 0 ? $data['cs_id'] : $pid,
            ];

            //获取储存对应数据库名
            $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
            $sqlname = 'chatlog'.$data['cs_id'] % 10;
            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
            $this->mo_send_type($author_wx['id'], $author_wx['uid']);
            // $ret = Db::name('chatlog')->insert($post_arr);
            if ($ret) {
                return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $keyword, 'send_time' => time(),'media_id'=>$chat_resource['media_id']], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'send error'], JSON_UNESCAPED_UNICODE);
        }
    }

    protected function resource_bk($data, $file, $type)
    {
        // file_put_contents('./requestMsgError.log','['.date("Y-m-d H:i:s").'] appid:'.$data['appid']."\n",FILE_APPEND);
        $appid = $data['appid'];
        $openid = $data['openid'];
        $chat_upload = new Chatupload();
        if ($type == 'image') {
            $keyword_arr = $chat_upload->upload($file);
            // $keyword_arr = $file;
        } elseif ($type == 'voice') {
            $keyword_arr = $chat_upload->voiceUpload($file);
        }

        if ($keyword_arr['error'] == 0) {
            $keyword = $keyword_arr['url'];
        } else {
            return false;
        }
        $customerService = isset($data['customerService']) ? $data['customerService'] : '';
        $author_wx = M('author_wx_user')->where('appid', $appid)->where('authorized', 1)->find();
        $wechatObj = new WechatThirdUtil($this->config, $author_wx);
        if (!empty($customerService)) {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->appointSendMediaToOne($openid, $chat_resource['media_id'], $type, $customerService);
        } else {
            $chat_resource = $wechatObj->uploadTempMaterial('.'.$keyword, $type);
            $result = $wechatObj->sendMediaToOne($openid, $chat_resource['media_id'], $type);
        }

        if ($result) {
            $pid = $this->csuser_model->where('id', $data['cs_id'])->value('pid');
            $post_arr = [
                'type' => $data['type'],
                'content' => $keyword, //图片路径
                'openid' => $data['openid'], //用户openid
                'appid' => $data['appid'], //对应公众号appid
                'cs_id' => $data['cs_id'], //客服id
                'send_time' => isset($data['send_time']) ? $data['send_time'] : time(), //发送时间
                'send_type' => '1002',
                'pid' => $pid == 0 ? $data['cs_id'] : $pid,
            ];

            //获取储存对应数据库名
            $this->users_model->where('openid', $openid)->update(['groupid' => 1]);
            $sqlname = 'chatlog'.$data['cs_id'] % 10;
            $ret = Db::connect('db_config_chatlog')->name($sqlname)->insert($post_arr);
            $this->mo_send_type($author_wx['id'], $author_wx['uid']);
            // $ret = Db::name('chatlog')->insert($post_arr);
            if ($ret) {
                return json_encode(['status' => 1, 'msg' => 'ok', 'path' => $keyword, 'send_time' => time()], JSON_UNESCAPED_UNICODE);
            }
        } else {
            return json_encode(['status' => -1, 'error' => 'send error'], JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 获取公众号openid.
     */
    public function getOpenidAll()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $where = [
                'subscribe' => ['eq', 1],
                'auid' => ['eq', $id],
            ];
            $openid = $this->users_model->where('auid', $id)->column('openid');
            if ($openid) {
                return json(['status' => 1, 'msg' => 'ok', 'result' => $openid]);
            }

            return json(['status' => -1, 'error' => 'not find openid']);
        }
    }

    /**
     * 实时监控发送消息.
     */
    private function mo_send_type($author_id, $uid)
    {
        $arr_data = [
            'type' => 'current_msg_count',
            'data' => [
                'id' => $author_id,
                'uid' => $uid,
            ],
        ];
        sendWebSocket($arr_data);
    }

    // ---------------------------------------- copy 從 wechatThirdLogic 的發送消息的方法 start ----------------------- //
    /**
     * 发送消息.
     */
    private function send($url, $post_arr)
    {
        $result = httpRequest($url, 'POST', $post_arr);
        if (!$result) {
            return false;
        }

        return $result;
    }
// ---------------------------------------- copy 從 wechatThirdLogic 的發送消息的方法 end ----------------------- //
    // 外部注册功能, 目前只有ae是开启的
    public function try_user(){
        if($this->request->isPost()){
            $data = $this->request->param();

            // 查看是否存在用户了
            $has_user = $this->has_user($data['username']);
            if($has_user){
                return json_encode(['status' => 401, 'msg' => '用户已经存在', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
            }else {
                $where = [
                    'password' => md5($data['password'] . Config::get('salt')),
                    'create_time' =>  date('Y-m-d H:i:s') ,
                    'username'  => $data['username'],
                    'status'    =>   3
                ];

                $admin_add = $this->admin_user_model->allowField(true)->save($where);
                if ($admin_add) {
                    $auth_group_access = [
                        'uid' => $this->admin_user_model->id,'group_id'=> 2
                    ];
                    $this->auth_group_access_model->save($auth_group_access);
                    return json_encode(['status' => 1, 'msg' => '注册成功', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }else{
                    return json_encode(['status' => 404, 'msg' => '注册失败', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
                }
            }
        }else{
            return json_encode(['status' => 301, 'msg' => '非法请求', 'send_time' => time()], JSON_UNESCAPED_UNICODE);
        }
    }

    public function has_user($username) {
        $result = $this->admin_user_model->where('username',$username)->find();
        return $result;
    }

}
